package cn.picclife.mwx.app.util;

import java.net.SocketTimeoutException;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
  
/** 
 * 公众平台通用接口工具类 
 *  jiangfeng
 *  2016.2.25
 */  
public class HttpsUtil {  
	
	//无返回值
	 public static final int SC_NO_CONTENT = 204;

	/***
	 * 发起https Post请求
	 * @param requestUrl 请求地址 
	 * @param headers  請求頭信息
	 * @param reqParamsJson 請求參數Json字符串
	 * @param backParams 返回值类型    0 是有返回值   1 是没有返回值
	 * @return
	 */
/*    public static String httpsPostRequest(String requestUrl,Map<String,String> headers,String reqParamsJson,int backParams) {
        String json = null;
	    HttpClient httpClient = new DefaultHttpClient();
	    MyX509TrustManager xtm = new MyX509TrustManager();
	    
	    try {
	    //TLS1.0与SSL3.0基本上没有太大的差别，可粗略理解为TLS是SSL的继承者，但它们使用的是相同的SSLContext
	    SSLContext ctx = SSLContext.getInstance("TLS");
	    //使用TrustManager来初始化该上下文，TrustManager只是被SSL的Socket所使用
	    ctx.init(null, new TrustManager[]{xtm}, null);
	    //创建SSLSocketFactory
	    SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
	    
	    //通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上
	    httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));
	    HttpPost httpPost = new HttpPost(requestUrl);                      
	   
	    //填充請求頭信息
	    if(headers!=null && headers.size()>0) {
	    	for(Entry<String, String> m:headers.entrySet()){
	    		 httpPost.setHeader(m.getKey(),m.getValue());
	    	}
	    }
	   
	   StringEntity entity = new StringEntity(reqParamsJson,"utf-8");    
       entity.setContentEncoding("UTF-8");    
       entity.setContentType("application/json");    
       httpPost.setEntity(entity); 

	   HttpResponse response = httpClient.execute(httpPost); 
	   
		try {
			if(SC_NO_CONTENT==response.getStatusLine().getStatusCode()){
				json ="success";
			}else{
				json = EntityUtils.toString(response.getEntity(), "utf-8");
			}
		}catch (Exception e) {
			e.printStackTrace();
	    }
    }catch (Exception e) {
		e.printStackTrace();
	}finally{
		httpClient.getConnectionManager().shutdown();
	}
	return json;
  }*/
    
    /***
	 * 发起https put请求
	 * @param requestUrl 请求地址 
	 * @param headers  请求头信息
	 * @param reqParamsJson 请求参数Json字符串
	 * @return
	 */
    /*public static String httpsPutRequest(String requestUrl,Map<String,String> headers,String reqParamsJson) {
        String json = null;
	    HttpClient httpClient = new DefaultHttpClient();
	    MyX509TrustManager xtm = new MyX509TrustManager();
	    
	    try {
	    //TLS1.0与SSL3.0基本上没有太大的差别，可粗略理解为TLS是SSL的继承者，但它们使用的是相同的SSLContext
	    SSLContext ctx = SSLContext.getInstance("TLS");
	    //使用TrustManager来初始化该上下文，TrustManager只是被SSL的Socket所使用
	    ctx.init(null, new TrustManager[]{xtm}, null);
	    //创建SSLSocketFactory
	    SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
	    
	    //通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上
	    httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));
	    HttpPut httpPut = new HttpPut(requestUrl);                      
	   
	    //填充請求頭信息
	    if(headers!=null && headers.size()>0) {
	    	for(Entry<String, String> m:headers.entrySet()){
	    		httpPut.setHeader(m.getKey(),m.getValue());
	    	}
	    }
	   
	   StringEntity entity = new StringEntity(reqParamsJson,"utf-8");    
       entity.setContentEncoding("UTF-8");    
       entity.setContentType("application/json");    
       httpPut.setEntity(entity); 

	   HttpResponse response = httpClient.execute(httpPut); 
		try {
			if(SC_NO_CONTENT==response.getStatusLine().getStatusCode()){
				json ="success";
			}else{
				json = EntityUtils.toString(response.getEntity(), "utf-8");
			}
			
		}catch (Exception e) {
			e.printStackTrace();
	    }
    }catch (Exception e) {
		e.printStackTrace();
	}finally{
		httpClient.getConnectionManager().shutdown();
	}
	return json;
  }*/
    
    
    /** 
     * 发送一个 GET 请求 
     *  
     * @param url 
     * @param charset 
     * @param connTimeout  建立链接超时时间,毫秒. 
     * @param readTimeout  响应超时时间,毫秒. 
     * @return 
     * @throws ConnectTimeoutException   建立链接超时 
     * @throws SocketTimeoutException   响应超时 
     * @throws Exception 
     */  
    public static String httpsGetRequest(String url, String charset,Map<String,String> headers, Integer connTimeout,Integer readTimeout) 
            throws ConnectTimeoutException,SocketTimeoutException, Exception { 
        
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);  
        String result = "";  
        MyX509TrustManager xtm = new MyX509TrustManager();
        try {  
            // 设置参数  
            Builder customReqConf = RequestConfig.custom();  
            if (connTimeout != null) {  
                customReqConf.setConnectTimeout(connTimeout);  
            }  
            if (readTimeout != null) {  
                customReqConf.setSocketTimeout(readTimeout);  
            }  
            get.setConfig(customReqConf.build());  
            
            //填充請求頭信息
    	    if(headers!=null && headers.size()>0) {
    	    	for(Entry<String, String> m:headers.entrySet()){
    	    		get.setHeader(m.getKey(),m.getValue());
    	    	}
    	    }
            HttpResponse res = null;  
            if (url.startsWith("https")) {  
                // 执行 Https 请求.  
            	//TLS1.0与SSL3.0基本上没有太大的差别，可粗略理解为TLS是SSL的继承者，但它们使用的是相同的SSLContext
        	    SSLContext ctx = SSLContext.getInstance("TLS");
        	    //使用TrustManager来初始化该上下文，TrustManager只是被SSL的Socket所使用
        	    ctx.init(null, new TrustManager[]{xtm}, null);
        	    //创建SSLSocketFactory
        	    SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
        	    
        	    //通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上
        	    client.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));
        	    
                res = client.execute(get); 
                result = IOUtils.toString(res.getEntity().getContent(), charset); 
            }
        } finally {  
            get.releaseConnection();  
            if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {  
                ((CloseableHttpClient) client).close();  
            }  
        }  
        return result;  
    } 
    
    /** 
     * 发送一个 delete 请求 
     * @param url 
     * @param charset 
     * @param connTimeout  建立链接超时时间,毫秒. 
     * @param readTimeout  响应超时时间,毫秒. 
     * @return 
     * @throws ConnectTimeoutException   建立链接超时 
     * @throws SocketTimeoutException   响应超时 
     * @throws Exception 
     */  
    public static String httpsDeleteRequest(String url, String charset,Map<String,String> headers, Integer connTimeout,Integer readTimeout) 
            throws ConnectTimeoutException,SocketTimeoutException, Exception { 
        
        HttpClient client = new DefaultHttpClient();
        HttpDelete del = new HttpDelete(url);  
        String result = "";  
        MyX509TrustManager xtm = new MyX509TrustManager();
        try {  
            // 设置参数  
            Builder customReqConf = RequestConfig.custom();  
            if (connTimeout != null) {  
                customReqConf.setConnectTimeout(connTimeout);  
            }  
            if (readTimeout != null) {  
                customReqConf.setSocketTimeout(readTimeout);  
            }  
            del.setConfig(customReqConf.build());  
            
            //填充請求頭信息
    	    if(headers!=null && headers.size()>0) {
    	    	for(Entry<String, String> m:headers.entrySet()){
    	    		del.setHeader(m.getKey(),m.getValue());
    	    	}
    	    }
            HttpResponse res = null;  
            if (url.startsWith("https")) {  
                // 执行 Https 请求.  
            	//TLS1.0与SSL3.0基本上没有太大的差别，可粗略理解为TLS是SSL的继承者，但它们使用的是相同的SSLContext
        	    SSLContext ctx = SSLContext.getInstance("TLS");
        	    //使用TrustManager来初始化该上下文，TrustManager只是被SSL的Socket所使用
        	    ctx.init(null, new TrustManager[]{xtm}, null);
        	    //创建SSLSocketFactory
        	    SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
        	    
        	    //通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上
        	    client.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));
        	    
                res = client.execute(del); 
                if(SC_NO_CONTENT==res.getStatusLine().getStatusCode()){
                	result ="success";
    			}else{
    				result = EntityUtils.toString(res.getEntity(), "utf-8");
    			}
            }
        } finally {  
        	del.releaseConnection();  
            if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {  
                ((CloseableHttpClient) client).close();  
            }  
        }  
        return result;  
    } 
    
    
}
